/**
 * 
 */
package com.googlecode.agiletools.codereview;

import java.util.Calendar;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Administrator
 * 
 */
public class ReviewRecordManager {

    private HibernateTemplate hibernateTemplate;

    /**
     * @param hibernateTemplate
     *            the hibernateTemplate to set
     */
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
	this.hibernateTemplate = hibernateTemplate;
    }

    /**
     * Create or update the review record.
     * 
     * @param reviewRecord
     * @return
     */
    @Transactional(readOnly = false)
    public ReviewRecord save(ReviewRecord reviewRecord) {
	if (reviewRecord == null) {
	    throw new IllegalArgumentException(
		    "Parameter reviewRecord can not be null.");
	}
	reviewRecord.setDate(Calendar.getInstance().getTime());
	System.out.println("ID is " + reviewRecord.getId());
	if (reviewRecord.getId() > 0) {
	    hibernateTemplate.merge(reviewRecord);
	} else {
	    hibernateTemplate.persist(reviewRecord);
	}
	return reviewRecord;
    }

    /**
     * @param recordId
     * @return
     */
    public ReviewRecord get(int recordId) {
	return (ReviewRecord) hibernateTemplate.get(ReviewRecord.class,
		recordId);
    }

    /**
     * Find review record of a special range.
     * 
     * @param firstResult
     * @param maxResults
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<ReviewRecord> find(String file, Integer revision,
	    int firstResult, int maxResults) {
	ReviewRecord example = new ReviewRecord();
	example.setFile(file);
	example.setRevision(revision);
	return hibernateTemplate
		.findByExample(example, firstResult, maxResults);
    }

    /**
     * Get the total count of review records.
     * 
     * @return the total count.
     */
    @SuppressWarnings("unchecked")
    public long totalCount() {
	// TODO Auto-generated method stub
	List list = hibernateTemplate.find("select count(*) from ReviewRecord");
	if (!list.isEmpty()) {
	    return (Long) list.get(0);
	} else {
	    return 0;
	}
    }

}
